<!-- 学生学习详情页面，应该根据的是 通过三个id查询一条数据(courseId,chapterId,sectionId) -->
<template>
  <div class="header">
    <el-affix :offset="1" z-index="999">
      <el-row class="header-row">
        <el-col :span="3" class="header-left">
          <div>
            <!-- 返回逻辑错误 -->
            <el-link class="subBack" @click="backToCourse()">
              <i>
                <el-icon><DArrowLeft /></el-icon
              ></i>
              返回课程
            </el-link>
          </div>
        </el-col>
        <el-col :span="18" class="header-center"> 章节详情 </el-col>
        <el-col :span="3" class="header-right"
          ><el-button text @click="test()" style="background: #fff"
            >侧边栏</el-button
          ></el-col
        >
      </el-row>
    </el-affix>
  </div>
  <div class="context">
    <el-container style="height: 100%">
      <el-affix :offset='offset'>
        <el-aside class="aside" id="aside">
          <el-card class="box-card" body-style="padding:0px">
            <div class="card-header">
              <el-button class="button" text>目录</el-button>
            </div>
            <el-scrollbar height="550px">
              <div
                class="catalogue"
                v-for="(item, index) in chapterList"
                :key="index"
              >
                <div class="fa" @click="fold($event)">
                  <el-icon><CaretBottom /></el-icon>{{ index + 1 }}
                  {{ item.title }}
                </div>
                <transition>
                  <div>
                    <div
                      class="so"
                      v-for="(item1, index1) in item.child"
                      :key="index1"
                      @click="showContent(item1)"
                    >
                      {{ index + 1 }}.{{ index1 + 1 }} {{ item1.title }}
                    </div>
                  </div>
                </transition>
              </div>
            </el-scrollbar>
          </el-card>
        </el-aside></el-affix>
      <el-main class="main">
        <div class="main-box">
          <div class="main-session">
            <div class="prev_title">
              {{ session.title }}
              <el-button
                text
                type="primary"
                style="float: right"
                @click="edit()"
                v-if="role == 'teacher'"
                >编辑</el-button
              >
            </div>
          </div>
          <div class="markdown-container">
            <div v-highlight v-html="md" class="markdown-body"></div>
          </div>
          <el-backtop :right="100" :bottom="100" />
        </div>
      </el-main>
    </el-container>
  </div>
  <div>
    <el-dialog title="上传文件" v-model="dialogFormVisible">
      <el-upload
        class="upload-demo"
        drag
        ref="uploadDemo"
        :headers="headerObj"
        action="http://localhost:8088/api/chapter/edit"
        :file-list="fileList"
        :data="chapterData"
        :before-upload="beforUpload"
        :limit="1"
        :on-exceed="exceed"
        :auto-upload="false"
        accept=".md"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          Drop file here or <em>click to upload</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            files with a size less than 10G
            <el-button
              size="small"
              style="margin-left: 50px"
              @click="dialogFormVisible = false"
              >取 消</el-button
            >
            <el-button size="small" type="primary" @click="upload1"
              >确 定</el-button
            >
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import "github-markdown-css";
const { marked } = require("marked");
import { useRoute } from "vue-router";
import { getChapters, seeionEdit } from "@/api/course";
import MyCollapse from "@/components/myComponent/myCollapse.vue";
import { ElMessage } from "element-plus";
import { mapGetters } from "vuex";
export default {
  components: {
    MyCollapse,
  },
  // 用于管理课程内容的编辑操作模块
  // 数据源
  data() {
    return {
      headerObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      offset:10,
      courseId: "",
      chapterId: "",
      sectionId: "",
      chapterList: [],
      originList: [], //最原始的目录结构，每一条每一条，并没有合并成树形结构，后面的方法都是围绕其进行
      session: {},
      md: "",
      dialogFormVisible: false,
      chapterData: {},
      fileList: [],
    };
  },
  beforeCreate() {
    marked.setOptions({
      gfm: true, //默认为true。 允许 Git Hub标准的markdown.
      tables: true, //默认为true。 允许支持表格语法。该选项要求 gfm 为true。
      breaks: false, //默认为false。 允许回车换行。该选项要求 gfm 为true。
      pedantic: false, //默认为false。 尽可能地兼容 markdown.pl的晦涩部分。不纠正原始模型任何的不良行为和错误。
      sanitize: false, //对输出进行过滤（清理）
      smartLists: true,
      smartypants: false, //使用更为时髦的标点，比如在引用语法中加入破折号。
    });
  },
  created() {
    this.getParams();
  },
  //生命周期函数---
  mounted() {},
  //基本方法
  methods: {
    compare(key) {
      return function (value1, value2) {
        let a = Number(value1[key]);
        let b = Number(value2[key]);
        if (a > b) {
          return 1;
        } else if (a < b) {
          return -1;
        } else {
          return 0;
        }
      };
    },
    getParams() {
      const route = useRoute();
      this.courseId = route.query.courseId;
      this.chapterId = route.query.chapterId;
      this.sectionId = route.query.sectionId;
      this.getChapterList();
    },
    test() {
      let aside = document.getElementById("aside");
      aside.classList.toggle("showAndHide");
    },
    getChapterList() {
      let that = this;
      getChapters({ courseId: that.courseId }).then((res) => {
        if (res.code == 200) {
          that.originList = res.data;
          that.initChapterList();
          this.chapterList.sort(this.compare("chapterId"));
          this.father.sort(this.compare("value"));
          // 初始化点击的信息
          for (const item of that.chapterList)
            for (const item1 of item.child) {
              if (
                item1.chapterId == that.chapterId &&
                item1.sectionId == that.sectionId
              ) {
                that.session = item1;
                that.md = marked(that.session.context.context);
              }
            }
        } else {
          ElMessage({
            type: "error",
            message: "获取列表失败",
          });
        }
      });
    },
    initChapterList() {
      this.chapterList = this.originList.filter((item) => item.sectionId == 0);
      for (const item of this.chapterList) {
        item.child = this.backChild(item.chapterId);
      }
      this.father = [];
      for (const item of this.chapterList) {
        this.father.push({ value: item.chapterId, label: item.title });
      }
    },
    backChild(id) {
      return this.originList.filter(
        (item) => item.chapterId == id && item.sectionId != 0
      );
    },
    showContent(item) {
      console.log(item);
      this.$router.push({
        name: "studentStudy",
        query: {
          courseId: item.courseId,
          chapterId: item.chapterId,
          sectionId: item.sectionId,
        },
      });
      this.chapterId = item.chapterId;
      this.sectionId = item.sectionId;
      this.session = item;
      this.md = item.context.context;
    },
    //确定上传文件 打开框框
    edit() {
      this.dialogFormVisible = true;
    },
    exceed() {
      ElMessage({
        type: "warning",
        message: "一次只能上传一个文件",
      });
    },
    // 对选中文件进行上传
    upload1() {
      //手动提交上传
      this.$refs.uploadDemo.submit();
      //需要处理解析文档
    },
    //上传前需要处理chapterData字段
    beforUpload(file) {
      // 解析上传的文件
      let reader = new FileReader();
      reader.readAsText(file);
      reader.onload = (val) => {
        this.chapterData.courseId = this.courseId;
        this.chapterData.chapterId = this.chapterId;
        this.chapterData.sectionId = this.sectionId;
        this.chapterData.context = { context: marked(reader.result) };
        // this.chapterData.context=JSON.stringify({"context":marked(reader.result)})
        seeionEdit(this.chapterData).then((res) => {
          if (res.code == "200") {
            ElMessage({
              type: "success",
              message: "上传成功",
            });
            this.fileList = [];
            this.md = marked(this.chapterData.context.context);
            this.session.context = this.chapterData.context;
          } else {
            this.fileList = [];
            ElMessage({
              type: "error",
              message: "上传失败",
            });
          }
          this.dialogFormVisible = false;
        });
      };
    },
    fold(ev) {
      let node = ev.target.nextElementSibling;
      if (node) {
        node.classList.toggle("showAndHide");
      }
    },
    //返回课程
    backToCourse() {
      this.$router.push({
        name: "chapters",
        query: {
          courseId: this.courseId,
        },
      });
    },
  },
  computed: {
    ...mapGetters({
      role: "getRole",
    }),
  },
};
</script>

<style   scoped>
a {
  text-decoration: none;
}

.subBack {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.7);
  margin-left: 30px;
  position: absolute;
  left: 0;
  top: 0;
}
.header {
  height: 45px;
  background: #3a4357;
  text-align: center;
  line-height: 45px;
  font-size: 16px;
  color: #a8a8b3;
}
.header-row {
  background: rgb(58, 67, 87);
}

.aside {
  min-height: 850px;
}

.main {
  background: rgb(238, 242, 245);
  width: 40%;
}
.box-card {
  min-height: 300px;
}
.catalogue {
  text-align: left;
}
.fa,
.so {
  line-height: 40px;
  height: 40px;
  cursor: pointer;
  user-select: none;
}
.fa {
  padding: 0 40px 0 20px;
  font-weight: 600;
  background: #f8f9fa;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  font-size: 14px;
  color: #181e33;
}
.so {
  padding: 0 40px 0 40px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.fa:hover {
  color: rgb(93, 97, 112);
  background: #f7fafc;
}
.so:hover {
  background: #f7fafc;
  color: rgb(0, 204, 126);
}
.card-header {
  overflow: hidden;
}
.main-box {
  margin-top: 30px;
  min-height: 400px;
  margin-left: 15%;
  margin-right: 15%;
  background: rgb(255, 255, 255);
}
.main-session {
  height: 80px;
  background: rgb(245, 248, 251);
}
.prev_title {
  padding: 12px 80px 8px;
  height: 56px;
  line-height: 56px;
  font-size: 18px;
  color: #333333;
  font-weight: 600;
  text-align: center;
  white-space: nowrap;
  text-overflow: ellipsis;
}
/* // 小节内容编辑样式表 */
.toolbar {
  height: 40px;
  font-size: 18px;
}
.el-row {
  height: 100%;
}
.el-col {
  height: 100%;
}
.cbox,
.hbox {
  display: flex;
  height: 100%;
}
.w-e-bar-item:hover {
  background: rgb(241, 241, 241);
}
.w-e-bar-item {
  align-items: center;
  justify-content: center;
  display: flex;
  position: relative;
  text-align: center;
  cursor: pointer;
}
.hhh {
  background: transparent;
  border: none;
  color: var(--w-e-toolbar-color);
  cursor: pointer;
  display: inline-flex;
  overflow: hidden;
  padding: 0 10px;
  white-space: nowrap;
  font-weight: bold;
  border-right: 1px solid #ccc;
}
pre {
  background: #181e33;
}
.showAndHide {
  display: none;
}
.v-enter-active,
.v-leave-active {
  transition: opacity 2s ease;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
}
.markdown-container {
  padding: 20px;
  text-align: left;
}
</style>